package tr.richfacesext.components.scrollhere;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.Renderer;

import tr.richfacesext.resourcemanagement.ResourceManager;
import tr.richfacesext.resourcemanagement.Resources;

/**
 * 
 * @author mert
 *
 */
public class ScrollHereRenderer extends Renderer {
	
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
		ResponseWriter writer = context.getResponseWriter();
		ScrollHere scrollhere = (ScrollHere) component;
		addResources();
		
		encodeScript(context, writer, scrollhere);
		encodeMarkup(context, writer, scrollhere);
	}

	private void encodeMarkup(FacesContext context, ResponseWriter writer, ScrollHere scrollhere) throws IOException {
		writer.write("<div id=\"" + scrollhere.getId() + "\"></div>\n");
	}

	private void encodeScript(FacesContext context, ResponseWriter writer, ScrollHere scrollhere) throws IOException {
		writer.startElement("script", scrollhere);
		writer.writeAttribute("type", "text/javascript", null);
		
		writer.write("" +
				"function " + scrollhere.getId() + "_scrollhere() {\n" +
				"\tvar obj = document.getElementById('" + scrollhere.getId() + "');\n" +
				"\tscrollHere(obj, obj);\n" +
				"}\n"+
				"\n" +
				"var " + scrollhere.getId() + "_oldonload = window.onload;\n" +
				"if (typeof window.onload != 'function') {\n" +
					"window.onload = " + scrollhere.getId() + "_scrollhere;" + "\n" +
				"}\n" +
				"else {\n" +
					"window.onload = function() {\n" +
						"if (" + scrollhere.getId() + "_oldonload) {\n" +
							scrollhere.getId() + "_oldonload();\n" +
						"}\n" +
						scrollhere.getId() + "_scrollhere()" + ";\n" +
					"}\n" +
				"}\n");
		writer.endElement("script");
	}
	
	private void addResources() {
		ResourceManager.addResource(Resources.SCROLLHERE_CORE_SCRIPT);
		ResourceManager.addResource(Resources.SCROLLHERE_ANIMATION_SCRIPT);
	}	
}